#include "DatabaseManager.h"
#include <QSqlQuery>
#include <QCryptographicHash>
#include <QDebug>

DatabaseManager& DatabaseManager::instance()
{
    static DatabaseManager instance;
    return instance;
}

DatabaseManager::DatabaseManager(QObject *parent) :
    QObject(parent),
    m_database(QSqlDatabase::addDatabase("QSQLITE"))
{
    m_database.setDatabaseName("flower_shop.db");
}

DatabaseManager::~DatabaseManager()
{
    if(m_database.isOpen()) {
        m_database.close();
    }
}

void DatabaseManager::initTables()
{
    QSqlDatabase db = instance().database();
    QSqlQuery query(db);

    // 用户表
    QString sql = "CREATE TABLE IF NOT EXISTS login_users ("
                  "id INTEGER PRIMARY KEY AUTOINCREMENT, "
                  "username TEXT UNIQUE NOT NULL, "
                  "password TEXT NOT NULL, "
                  "user_type TEXT NOT NULL DEFAULT 'user', "
                  "created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)";
    if (!query.exec(sql)) {
        qDebug() << "Error creating login_users table:" << query.lastError().text();
    }

    // 商品表
    sql = "CREATE TABLE IF NOT EXISTS products ("
          "product_id INTEGER PRIMARY KEY AUTOINCREMENT, "
          "name TEXT NOT NULL, "
          "price REAL, "
          "stock INTEGER, "
          "image_path TEXT, "
          "description TEXT, "
          "status TEXT DEFAULT 'active')";
    if (!query.exec(sql)) {
        qDebug() << "Error creating products table:" << query.lastError().text();
    }

    // 购物车表
    sql = "CREATE TABLE IF NOT EXISTS Cart ("
          "cart_id INTEGER PRIMARY KEY AUTOINCREMENT, "
          "user_id INTEGER NOT NULL, "
          "product_id INTEGER NOT NULL, "
          "quantity INTEGER NOT NULL, "
          "UNIQUE(user_id, product_id))";
    if (!query.exec(sql)) {
        qDebug() << "Error creating Cart table:" << query.lastError().text();
    }

    // 订单表
    sql = "CREATE TABLE IF NOT EXISTS Orders ("
          "orders_id INTEGER PRIMARY KEY AUTOINCREMENT, "
          "user_id INTEGER, "
          "total_price REAL NOT NULL, "
          "create_time DATETIME NOT NULL, "
          "status TEXT, "
          "address TEXT NOT NULL, "
          "phone TEXT NOT NULL, "
          "FOREIGN KEY(user_id) REFERENCES login_users(id))";
    if (!query.exec(sql)) {
        qDebug() << "Error creating Orders table:" << query.lastError().text();
    }

    // 订单详情表
    sql = "CREATE TABLE IF NOT EXISTS OrderDetails ("
          "order_detail_id INTEGER PRIMARY KEY AUTOINCREMENT, "
          "order_id INTEGER NOT NULL, "
          "product_id INTEGER NOT NULL, "
          "quantity INTEGER NOT NULL, "
          "FOREIGN KEY(order_id) REFERENCES Orders(orders_id), "
          "FOREIGN KEY(product_id) REFERENCES products(product_id))";
    if (!query.exec(sql)) {
        qDebug() << "Error creating OrderDetails table:" << query.lastError().text();
    }
}

bool DatabaseManager::initializeDatabase()
{
    if(!m_database.open()) {
        qCritical() << "数据库打开失败:" << m_database.lastError().text();
        return false;
    }

    QSqlQuery query;
    if(!query.exec("SELECT name FROM sqlite_master WHERE type='table' AND name='login_users'") || !query.next()) {
        if(!query.exec("CREATE TABLE login_users ("
                      "id INTEGER PRIMARY KEY AUTOINCREMENT, "
                      "username TEXT UNIQUE NOT NULL, "
                      "password TEXT NOT NULL, "
                      "user_type TEXT NOT NULL DEFAULT 'user', "
                      "created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)")) {
            qCritical() << "创建用户表失败:" << query.lastError().text();
            return false;
        }

        // 添加默认管理员账户
        QByteArray adminHash = QCryptographicHash::hash(
            "admin123", QCryptographicHash::Md5);
        query.prepare("INSERT INTO login_users (username, password, user_type) "
                     "VALUES ('admin', :password, 'admin')");
        query.bindValue(":password", adminHash.toHex());

        if(!query.exec()) {
            qCritical() << "添加管理员失败:" << query.lastError().text();
        } else {
            qDebug() << "默认管理员账户已创建 (用户名:admin 密码:admin123)";
        }
    }
    return true;
}

QSqlDatabase DatabaseManager::database() const
{
    return m_database;
}
